package com.liushuai.phoneguardian;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;

import com.liushuai.phoneguardian.domain.UpdateInfo;
import com.liushuai.phoneguardian.utils.CheckUpdateUtil;
import com.liushuai.phoneguardian.utils.CopyFileUtils;
import com.liushuai.phoneguardian.utils.DownLoadUtil;
import com.liushuai.phoneguardian.utils.InstallApk;

import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.text.AlteredCharSequence;
import android.util.Log;
import android.view.Menu;
import android.view.animation.AlphaAnimation;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class SplashActivity extends Activity {

	private static final String TAG = "SplashActivity";
	private TextView appnametx;
	private TextView tv_version;
	private UpdateInfo updateInfo;
	private ProgressDialog pd;
	private static final int DOWNLOAD_SUCCESS = 15;
	private static final int DOWNLOAD_ERROR = 16;
	protected static final int COPY_ERROR = 22;
	private Handler handler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			switch (msg.what) {
			case CheckUpdateUtil.PARSE_XML_ERROR:
				Toast.makeText(getApplicationContext(), "解析xml失败", 0).show();
				// 进入程序主界面
				loadUI();
				break;
			case CheckUpdateUtil.SERVER_ERROR:
				Toast.makeText(getApplicationContext(), "服务器异常", 0).show();
				// 进入程序主界面
				loadUI();
				break;
			case CheckUpdateUtil.URL_ERROR:
				Toast.makeText(getApplicationContext(), "服务器地址异常", 0).show();
				// 进入程序主界面
				loadUI();
				break;
			case CheckUpdateUtil.NETWORK_ERROR:
				Toast.makeText(getApplicationContext(), "网络异常", 0).show();
				// 进入程序主界面
				loadUI();
				break;
			case CheckUpdateUtil.NOT_UPDATE:
				Toast.makeText(getApplicationContext(), "未选择自动更新", 0).show();
				// 进入程序主界面
				loadUI();
				break;
			case CheckUpdateUtil.PARSE_XML_SUCCESS:
				updateInfo = (UpdateInfo) msg.getData().getSerializable(
						"updateinfo");
				if (returnAppVersion().equals(updateInfo.getVersion())) {
					// 进入程序主界面
					Log.i(TAG, "版本号相同,进入主界面");
					loadUI();
				} else {
					Log.i(TAG, "版本号不相同,弹出来升级提示对话框");
					showUpdateDiaLog();
				}
				break;
			case DOWNLOAD_SUCCESS:
				File file = (File) msg.obj;
				Log.i(TAG, "install" + file.getAbsolutePath());
				// 安装apk
				InstallApk.installApk(SplashActivity.this, file);
				finish();
				break;
			case DOWNLOAD_ERROR:
				Toast.makeText(getApplicationContext(), "下载失败", 0).show();
				// 进入程序主界面
				loadUI();
				break;
			case COPY_ERROR :
				Toast.makeText(getApplicationContext(), "copy is filed", Toast.LENGTH_SHORT).show();

			}
		}
	};

	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_splash);
		appnametx = (TextView) findViewById(R.id.tv_splash_appname);
		tv_version = (TextView) findViewById(R.id.tv_splash_version);
		appnametx.setText(getString(R.string.app_name));
		tv_version.setText("版本号" + returnAppVersion());

		new Thread(new CheckUpdateUtil(handler, this)).start();
		AlphaAnimation aa = new AlphaAnimation(0.2f, 1.0f);
		aa.setDuration(2000);
		findViewById(R.id.rl_splash).startAnimation(aa);

		// 拷贝文件到系统目录
		copyAddressDBtoCare();

	}

	private void copyAddressDBtoCare() {
		final File file = new File(getFilesDir(), "address.db");
		Message mes = Message.obtain();
		if (file.exists() && file.length() > 0) {
			// do nothing
		} else {
			new Thread() {
				public void run() {
					Message mes = Message.obtain();
					 
					try {
						InputStream is = getAssets().open("address.db");
						File f = CopyFileUtils.copyFile(is, file.getAbsolutePath());
						if(f!=null){
							
						}else{
							mes.what = COPY_ERROR;
						}
					} catch (Exception e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
						mes.what = COPY_ERROR;
					}finally{
						handler.sendMessage(mes);
					}
					
					
					
				};
			}.start();
		}
	}

	/**
	 * 
	 * @return 返回版本号
	 */
	public String returnAppVersion() {
		PackageManager pm = getPackageManager();
		try {
			PackageInfo packageInfo = pm.getPackageInfo(getPackageName(), 0);
			return packageInfo.versionName;
		} catch (NameNotFoundException e) {
			return "";
		}
	}

	/**
	 * 进入主界面
	 */
	public void loadUI() {
		Intent intent = new Intent(this, HomeActivity.class);
		startActivity(intent);
		finish();
	}

	/**
	 * 升级提醒对话框
	 */
	public void showUpdateDiaLog() {
		AlertDialog.Builder builder = new Builder(this);
		builder.setTitle("升级提醒");
		builder.setMessage(updateInfo.getDescription());

		builder.setPositiveButton("Sure", new OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				String apkurl = updateInfo.getApkurl();
				pd = new ProgressDialog(SplashActivity.this);
				pd.setTitle("升级操作");
				pd.setMessage("正在下载...");
				pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
				pd.show();
				Log.i(TAG, "下载后安装:" + apkurl);
				final File file = new File(Environment
						.getExternalStorageDirectory(), DownLoadUtil
						.getFileName(apkurl));
				if (Environment.getExternalStorageState().equals(
						Environment.MEDIA_MOUNTED)) {
					new Thread() {
						public void run() {
							super.run();
							File saveFile = DownLoadUtil.download(
									updateInfo.getApkurl(),
									file.getAbsolutePath(), pd);
							Message msg = Message.obtain();
							if (saveFile != null) {
								// 下载成功
								msg.what = DOWNLOAD_SUCCESS;
								msg.obj = saveFile;
							} else {
								// 下载失败
								msg.what = DOWNLOAD_ERROR;
							}
							handler.sendMessage(msg);
							pd.dismiss();
						};

					}.start();
				} else {
					Toast.makeText(getApplicationContext(), "sd卡不可用", 0).show();
					loadUI();
				}
			}
		});

		builder.setNegativeButton("Cancel", new OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {

				loadUI();
			}
		});

		builder.create().show();

	}

}
